Using FirstOrDefault
or SingleOrDefault
on collections that are known to be non-empty is an issue due to:
- Code Clarity and intent: When you use
FirstOrDefault
or SingleOrDefault
, it implies that the collection might be
empty, which can be misleading if you know it is not. It can be confusing for other developers who read your code, making it harder for them to
understand the actual constraints and behavior of the collection. This leads to confusion and harder-to-maintain code.
- Error handling: If the developer’s intend is for the collection not to be empty, using
FirstOrDefault
and
SingleOrDefault
can lead to subtle bugs. These methods return a default value (null
for reference types and
default
for value types) when the collection is empty, potentially causing issues like NullReferenceException
later in the
code. In contrast, First
or Single
will throw an InvalidOperationException
immediately if the collection is
empty, making it easier to detect and address issues early in the development process.
- Code coverage: Potentially, having to check if the result is
null
, you introduces a condition that cannot be fully tested,
impacting the code coverage.
Code examples
Noncompliant code example
var items = new List<int> { 1, 2, 3 };
int firstItem = items.FirstOrDefault(); // Noncompliant, this implies the collection might be empty, when we know it is not
Compliant solution
var items = new List<int> { 1, 2, 3 };
int firstItem = items.First(); // Compliant